package com.example.tao.mycar.activity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVUser;
import com.example.tao.mycar.MyActionBarActivity;
import com.example.tao.mycar.MyApplication;
import com.example.tao.mycar.R;
import com.example.tao.mycar.utils.FileUtils;
import com.example.tao.mycar.utils.PicOperator;
import com.example.tao.mycar.utils.RequestUtils;
import com.example.tao.mycar.view.dialog.CustomDialog;
import com.example.tao.mycar.view.dialog.PicChooserDialog;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class BabyInfoActivity extends MyActionBarActivity implements View.OnClickListener, RequestUtils.MyItemClickListener {

    RecyclerView mRecyclerView;
    MyAdapter mAdapter;
    LinearLayout inputName;
    TextView babyName;
    EditText editText;
    ImageView babyImage;
    DatePickerDialog mDatePickerDialog = null;
    String[] title = {"性别", "生日", "年龄", "身高", "体重"};
    private static final String FileFolderName = "MyCar";
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    private String SOURCE_IMAGE_FILE = "";
    private Uri SOURCE_IMAGE_URI = null;
    private String OUTPUT_IMAGE_FILE = "";
    private Uri OUTPUT_IMAGE_URI = null;

    Map<String, String> listItem = new HashMap<>();

    String userId = AVUser.getCurrentUser().getObjectId();
    private String HEAD_ICON_NAME = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(MyApplication.TAG, "BabyInfoActivity onCreate");
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_baby_info);
        setToolBar(getResources().getString(R.string.title_activity_baby_info), false);

        inputName = (LinearLayout)findViewById(R.id.input_name);
        babyName = (TextView)findViewById(R.id.baby_name);
        babyImage = (ImageView)findViewById(R.id.baby_image);

        inputName.setOnClickListener(this);
        babyImage.setOnClickListener(this);

        Log.d(MyApplication.TAG, "BabyInfoActivity initFilePath");
        initFilePath();
        if (FileUtils.fileExists(OUTPUT_IMAGE_FILE)) {
            Bitmap bitmap = PicOperator.decodeUriAsBitmap(this, OUTPUT_IMAGE_URI);
            babyImage.setImageBitmap(PicOperator.toRoundBitmap(bitmap));
        } else {
            babyImage.setImageResource(R.mipmap.personal_head_bg2_nor2x);
        }

        mRecyclerView = (RecyclerView)findViewById(R.id.baby_info_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            private Drawable mDivider = getResources().getDrawable(R.drawable.list_divider);

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
                final int left = parent.getPaddingLeft();
                final int right = parent.getWidth() - parent.getPaddingRight();
                final int childCount = parent.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    final View child = parent.getChildAt(i);
                    final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
                    final int top = child.getBottom() + params.bottomMargin;
                    final int bottom = top + mDivider.getIntrinsicHeight();
                    mDivider.setBounds(left, top, right, bottom);
                    mDivider.draw(c);
                }
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
            }
        });

        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    private void initFilePath() {
        if (userId != null) {
            HEAD_ICON_NAME = userId + "_head_icon.png";
        }
        SOURCE_IMAGE_FILE = FileUtils.gainSDCardPath() + File.separator + FileFolderName + File.separator + "temp.jpg";
        OUTPUT_IMAGE_FILE = FileUtils.gainSDCardPath() + File.separator + FileFolderName + File.separator + "icon" +
                File.separator + HEAD_ICON_NAME;
        File srcFile = new File(SOURCE_IMAGE_FILE);
        if (!srcFile.exists()) {
            srcFile.getParentFile().mkdirs();
        }
        File outFile = new File(OUTPUT_IMAGE_FILE);
        if (!outFile.exists()) {
            outFile.getParentFile().mkdirs();
        }
        SOURCE_IMAGE_URI = Uri.parse("file://" + SOURCE_IMAGE_FILE);
        OUTPUT_IMAGE_URI = Uri.parse("file://" + OUTPUT_IMAGE_FILE);
    }

    @Override
    protected void onResume() {
        Log.d(MyApplication.TAG, "BabyInfoActivity onResume");
        super.onResume();
        String babyNameStr = RequestUtils.getSharedPreference(BabyInfoActivity.this).getString(RequestUtils.BABYNAME, "宝宝昵称");
        String babyBirthdayStr = RequestUtils.getSharedPreference(BabyInfoActivity.this).getString(RequestUtils.BABYBIRTHDAY, null);
        String babySexStr = RequestUtils.getSharedPreference(BabyInfoActivity.this).getString(RequestUtils.BABYSEX, "小王子");
        babyName.setText(babyNameStr);

        listItem.put(title[0], babySexStr);
        listItem.put(title[1], babyBirthdayStr);
        listItem.put(title[2], "8个月17天");
        listItem.put(title[3], "68cm");
        listItem.put(title[4], "8.8kg");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.input_name :
                showInputBabyNameDialog();
                break;
            case R.id.baby_image :
                showPicChooserDialog();
                break;
            default:
                break;
        }
    }

    private void showPicChooserDialog() {
        final PicChooserDialog dialog;
        final PicChooserDialog.Builder builder = new PicChooserDialog.Builder(this);
        builder.setTitle("设置头像");
        builder.setButton1("相机", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, SOURCE_IMAGE_URI);
                Log.d(MyApplication.TAG, "open camera");
                startActivityForResult(cameraIntent, CODE_CAMERA_REQUEST);
                dialog.dismiss();
            }
        });

        builder.setButton2("相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                galleryIntent.setType("image/*");
                Log.d(MyApplication.TAG, "open gallery");
                startActivityForResult(galleryIntent, CODE_GALLERY_REQUEST);
                dialog.dismiss();
            }
        });

        builder.setButton3("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog = builder.create();
        dialog.show();;
    }

    private void showInputBabyNameDialog() {
        final CustomDialog customDialog;
        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("编辑宝宝昵称");
        builder.setShowEditView(true);
        builder.setShowSelectSex(false);
        builder.setShowButton(true);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (!TextUtils.isEmpty(editText.getText().toString())) {
                    String oldName = RequestUtils.getSharedPreference(BabyInfoActivity.this).getString(RequestUtils.BABYNAME, "宝宝昵称");
                    if (!(editText.getText().toString().equals(oldName))) {
                        babyName.setText(editText.getText().toString());
                        RequestUtils.getSharedPreferenceEditor(BabyInfoActivity.this).putString(RequestUtils.BABYNAME,
                                editText.getText().toString()).commit();
                    }
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        customDialog = builder.create();
        editText = (EditText)customDialog.findViewById(R.id.input_name);
        customDialog.show();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                builder.showKeyboard();
            }
        }, 200);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case 0 :
                showInputBabySexDialog();
                break;
            case 1 :
                if (mDatePickerDialog==null || !mDatePickerDialog.isShowing()) {
                    Calendar calendar = Calendar.getInstance();
                    mDatePickerDialog = new DatePickerDialog(BabyInfoActivity.this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String birthday = year + "年" + monthOfYear + "月" + dayOfMonth + "日";
                            RequestUtils.getSharedPreferenceEditor(BabyInfoActivity.this).putString(RequestUtils.BABYBIRTHDAY, birthday).commit();
                            listItem.put(title[1], birthday);
                            mAdapter.notifyDataSetChanged();
                            mDatePickerDialog = null;
                        }
                    }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                    mDatePickerDialog.show();
                }
                break;
            case 2 :

                break;
            case 3 :
                startActivity(new Intent(this, InputHeightActivity.class));
                break;
            case 4 :
                startActivity(new Intent(this, InputWeightActivity.class));
                break;
            default:
                break;
        }
    }

    private void showInputBabySexDialog() {
        final CustomDialog customDialog;
        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("性别");
        builder.setShowButton(false);
        builder.setShowEditView(false);
        builder.setShowSelectSex(true);
        customDialog= builder.create();

        final RadioGroup radioGroup = (RadioGroup)customDialog.findViewById(R.id.radio_group);
        RadioButton radioMale = (RadioButton)customDialog.findViewById(R.id.radio_male);
        RadioButton radioFemale = (RadioButton)customDialog.findViewById(R.id.radio_female);

        String babySex = RequestUtils.getSharedPreference(BabyInfoActivity.this).getString(RequestUtils.BABYSEX, "小王子");

        if ("小王子".equals(babySex)) {
            radioMale.setChecked(true);
        } else if ("小公举".equals(babySex)) {
            radioFemale.setChecked(true);
        }

        radioMale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        customDialog.dismiss();
                    }
                }, 300);
            }
        });

        radioFemale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        customDialog.dismiss();
                    }
                }, 300);
            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonId = group.getCheckedRadioButtonId();
                if (radioButtonId == R.id.radio_male) {
                    listItem.put(title[0], "小王子");
                    RequestUtils.getSharedPreferenceEditor(BabyInfoActivity.this).putString(RequestUtils.BABYSEX, "小王子").commit();
                    mAdapter.notifyDataSetChanged();
                } else if (radioButtonId == R.id.radio_female) {
                    listItem.put(title[0], "小公举");
                    RequestUtils.getSharedPreferenceEditor(BabyInfoActivity.this).putString(RequestUtils.BABYSEX, "小公举").commit();
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        customDialog.show();
    }

    private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        RequestUtils.MyItemClickListener mItemClickListener;

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(BabyInfoActivity.this).
                    inflate(R.layout.baby_info_list_item, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.babyInfoTitle.setText(title[position]);
            holder.babyInfo.setText(listItem.get(title[position]));
        }

        @Override
        public int getItemCount() {
            return listItem.size();
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {
            TextView babyInfoTitle, babyInfo;

            public MyViewHolder(View itemView) {
                super(itemView);
                babyInfoTitle = (TextView)itemView.findViewById(R.id.baby_info_title);
                babyInfo = (TextView)itemView.findViewById(R.id.baby_info);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mItemClickListener != null) {
                            mItemClickListener.onItemClick(view, getPosition());
                        }
                    }
                });
            }
        }

        public void setOnItemClickListener(RequestUtils.MyItemClickListener listener) {
            this.mItemClickListener = listener;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(MyApplication.TAG, "BabyInfoActivity onActivityResult");

        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
        }

        switch (requestCode) {
            case CODE_CAMERA_REQUEST :
                Log.d(MyApplication.TAG, "CODE_CAMERA_REQUEST");
                PicOperator.toCropImageActivity(this, SOURCE_IMAGE_URI, OUTPUT_IMAGE_URI, 300, 300, CODE_RESULT_REQUEST);
                break;
            case CODE_GALLERY_REQUEST :
                Log.d(MyApplication.TAG, "CODE_GALLERY_REQUEST");
                String path = FileUtils.getPath(this, data.getData());
                SOURCE_IMAGE_URI = Uri.parse("file://" + path);
                Log.d(MyApplication.TAG, path);
                PicOperator.toCropImageActivity(this, SOURCE_IMAGE_URI, OUTPUT_IMAGE_URI, 300, 300, CODE_RESULT_REQUEST);
                break;
            case CODE_RESULT_REQUEST :
                Log.d(MyApplication.TAG, "CODE_RESULT_REQUEST");
                if (OUTPUT_IMAGE_URI != null) {
                    Bitmap bitmap = PicOperator.decodeUriAsBitmap(this, OUTPUT_IMAGE_URI);
                    if (bitmap == null) {
                        return;
                    }
                    babyImage.setImageBitmap(PicOperator.toRoundBitmap(bitmap));
                }
                break;
        }
    }
}
